/*
 * Main model class
 * manage all the access from the controller to the others models
 */
package addressBook.model;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author mathieubakrim
 */
public class AddressBookModel {
    private final String fileName = "data1.csv";
    private ContactsTable contactsTable;
    private long executionTime, start;

    //Main list of contact used over the application
    private ArrayList<Contact> contactsList = new ArrayList<Contact>();
    private final String [] group = {"Friends", "family", "companies", "co-workers"};
    
    /**
     * Constructor of addressBookModel
     * Populate the application contact list
     */
    public AddressBookModel(){        
        try {
            csvReader();
        } catch (FileNotFoundException ex) {
            Logger.getLogger(AddressBookModel.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(AddressBookModel.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Csv reader used to read the data.csv file
     * @throws FileNotFoundException
     * @throws IOException 
     */
    public void csvReader() throws FileNotFoundException, IOException{
        start = System.currentTimeMillis();
        BufferedReader reader = new BufferedReader(new FileReader(fileName));
        String csvContacts = null;
        
        reader.readLine(); // avoid to retrieve the title line as a contact
        
        while((csvContacts = reader.readLine()) != null){
            
            String[] contactInfoData = csvContacts.split(";");
            
            final SimpleContact contact = new SimpleContact();
                
            contact.setLastName(contactInfoData[0]);
            contact.setFirstName(contactInfoData[1]);
            contact.setPhoneNumber(contactInfoData[2]);
            contact.setAddressPro(contactInfoData[3]);
            contact.setAddressPer(contactInfoData[4]);
            contact.setHomePage(contactInfoData[5]);
            contact.setEmailPro(contactInfoData[6]);
            contact.setEmailPer(contactInfoData[7]);
            contact.setGroup(contactInfoData[8]);
            
            contactsList.add(contact);
        }
        executionTime = System.currentTimeMillis() - start;
        System.out.println("csvReader execution time: " + executionTime + "ms");
    }
    
    /**
     * Csv writer usedto write the addressbook contact in a file
     * @throws IOException 
     */
    public void csvWriter() throws IOException{
        start = System.currentTimeMillis();
        char separator = ';';
        BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));
        for (String title : contactsTable.getTitles()) {
            writer.write(title + separator);
        }
        writer.newLine();
        
        for(int i = 0; i < contactsList.size(); i++){
            writer.write(contactsList.get(i).getLastName()+ separator);
            writer.write(contactsList.get(i).getFirstName()+ separator);
            writer.write(contactsList.get(i).getPhoneNumber()+ separator);
            writer.write(contactsList.get(i).getAddressPro()+ separator);
            writer.write(contactsList.get(i).getAddressPer()+ separator);
            writer.write(contactsList.get(i).getHomePage() + separator);
            writer.write(contactsList.get(i).getEmailPro() + separator);
            writer.write(contactsList.get(i).getEmailPer()+ separator);
            writer.write(contactsList.get(i).getGroup()+ separator);
            writer.newLine();
        }
        
        writer.close();
        executionTime = System.currentTimeMillis() - start;
        System.out.println("csvWriter execution time: " + executionTime + "ms");
    }
    
    /**
     * Create a contact with data read from the controller
     * This is the time consuming operation
     * @param ln
     * @param fn
     * @param pn
     * @param ap
     * @param ape
     * @param hp
     * @param ep
     * @param epe
     * @param gr
     * @return a contact
     */
     public Contact createContact(String ln, String fn, String pn, String ap, String ape, String hp, String ep, String epe, String gr) {
           
         Contact c = new SimpleContact(ln, fn, pn, ap, ape, hp, ep, epe, gr);
         start = System.currentTimeMillis(); 
         contactsList.add(c);
         
         executionTime = System.currentTimeMillis() - start;
         System.out.println("createContactModel execution time: " + executionTime + "ms");
         return c;
     }  
     
        /**
     * Delete a contact
     * @param c 
     */
    public void deleteContact(Contact c){
        contactsList.remove(c);
    }
    
     /**
     * Create the contact table model for the view
     * @param tab_string
     * @param contacts
     * @return a contactTable model
     */
    public ContactsTable createContactTable(String[] tab_string, ArrayList<Contact> contacts) {
        contactsTable = new ContactsTable(tab_string, contacts);
        return contactsTable;
    }
    
    // GETTERS
    public String[] getGroup() {
        return group;
    }
    /**
     * Getter
     * @return List of contacts actually saved in memory
     **/
    public ArrayList<Contact> getContactsList() {
        return contactsList;
    } 
    public void setContactsList(List<Contact> contactsList) {
        this.contactsList = (ArrayList<Contact>)contactsList;
    }


   
}


